package io.github.godfather1103.macro

import com.intellij.codeInsight.template.*
import com.intellij.psi.PsiMethod

/**
 * <p>Title:        Godfather1103's Github</p>
 * <p>Copyright:    Copyright (c) 2023</p>
 * <p>Company:      https://github.com/godfather1103</p>
 *
 * @author  作者: Jack Chu E-mail: chuchuanbao@gmail.com
 * @date 创建时间：2023/8/18 13:41
 * @version 1.0
 * @since  1.0
 */
class MethodExceptionsMacro : Macro() {
    override fun getName(): String = "methodExceptions"

    override fun getDefaultValue(): String = "[Exception]"

    override fun getPresentableName(): String = "methodExceptions(Boolean)"

    override fun calculateResult(params: Array<out Expression>, context: ExpressionContext?): Result? {
        var place = context?.psiElementAtStartOffset
        var returnSimple = true
        if (params.isNotEmpty()) {
            returnSimple = params[0].calculateResult(context).toString().toBoolean()
        }
        while (place != null) {
            if (place is PsiMethod) {
                val result: MutableList<Result> = mutableListOf()
                val project = place.getProject()
                place.throwsList.referencedTypes.forEach {
                    if (returnSimple) {
                        result.add(TextResult(it.className))
                    } else {
                        result.add(PsiTypeResult(it, project))
                    }
                }
                return ListResult(result)
            }
            place = place.parent
        }
        return null
    }

    override fun isAcceptableInContext(context: TemplateContextType?): Boolean {
        return context is JavaCodeContextType
    }
}